<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/17
 * Time: 19:16
 * 钱包常用数据函数
 */

namespace common\models\Service;


use common\models\CommonFunction;
use common\models\DAO\BrokageClear;
use common\models\DAO\DayAccrual;
use common\models\DAO\FinanceStaff;
use common\models\DAO\HongbaoSendAccrual;
use common\models\DAO\UserCharge;
use common\models\DAO\UserFreeze;
use common\models\DAO\UserInvestList;
use common\models\DAO\UserProceeds;
use common\models\DAO\UserTransferList;
use common\models\DAO\UserWalletLog;
use common\models\DAO\FinanceRemainder;

class Wallet {

    public static function clear($userID, $adminID){
        $brokage = self::brokerage($userID);
        if($brokage == 0)
            return true;
        $transaction = \Yii::$app->db->beginTransaction();
        $brokage = new BrokageClear();
        $brokage->userID = $userID;
        $brokage->adminID = $adminID;
        $brokage->money = $brokage;
        $brokage->createTime = time();
        $brokage_result = $brokage->save();
        if(!$brokage_result){
            $transaction->rollBack();
            return false;
        }
        $db = \Yii::$app->db;
        $userID = intval($userID);
        $result = $db->createCommand("update p2p_day_accrual set money=0 where userID={$userID} and chargeID=0 and money!=0")->execute();
        if(!$result){
            $transaction->rollBack();
            return false;
        }
        return true;
    }

    /*
     * 冻结资金
     */
    public static function freeze($userID){
        $money = 0;
        $user = UserFreeze::findOne($userID);
        $user && $money = $user['money'];
        return $money;
    }

    /*
     * 获取账户红包佣金
     */
    public static function brokerage($userID){
        $accrual = DayAccrual::find()->where(array('userID'=>$userID))->andWhere('(senduserID!=0 OR typeID=11 OR typeID=13)')->groupBy('userID')
            ->select('SUM(invest) as money, userID')
            ->one();
        if($accrual){
            $accrual = $accrual->attributes;
            return intval($accrual['money']);
        }else
            return 0;
    }

    /*
     * 用户发红包钱包金额
     *
     */
    public static function send($userID){
        $money = 0;
        $result = HongbaoSendAccrual::find()->where(['userID'=>$userID])->sum('money');
        $result && $money = intval($result);
        return $money;
    }

    /*
     * 获取账户余额
     */
    public static function remainder($userID){
        $accrual = DayAccrual::find()->where(array('userID'=>$userID))->andFilterWhere(['>', 'money', 0])->groupBy('userID')
            ->select('SUM(money) as money, userID')
            ->one();
        if($accrual){
            $accrual = $accrual->attributes;
            return intval($accrual['money']);
        }else
            return 0;
    }

    /*
     * 获取账户余额
     */
    public static function companyRemainder($companyID){
        $accrual = FinanceRemainder::find()->where(['companyID'=>$companyID])->andFilterWhere(['>', 'money', 0])->asArray()
            ->sum('money');
        if($accrual){
            return intval($accrual);
        }else
            return 0;
    }

    /*
     * 可提现账户余额
     */
    public static function can_remainder($userID){
        $date = intval(date('Ymd'));
        $accrual = DayAccrual::find()->where(['userID'=>$userID])->andWhere("money > 0 and (chargeID != 0 AND date < $date) OR chargeID=0")
            ->sum('money');
        if($accrual){
            return intval($accrual);
        }else
            return 0;
    }


    /*
     * 昨日收益
     */
    public static function getAccrual($userID){
        $today = date("Ymd",strtotime("-1 day"));
        $proceeds = UserProceeds::findOne(array('userID'=>$userID, 'createTime'=>$today));
        $money = 0;
        if($proceeds){
            $proceeds = $proceeds->attributes;
            $money = $proceeds['money'];
        }
        return $money;
    }

    /*
     * 所有收益
     */
    public static function tatalAccrual($userID){
        $proceeds = UserProceeds::find()->where(['userID'=>$userID])->sum('money');
        $money = 0;
        if($proceeds){
            $money = $proceeds;
        }
        return $money;
    }

    /*
     * 钱包扣钱
     */
    public static function deduct($param, $order = 'asc'){
        //更新用户余额 - 扣除账户余额
        $user_invest_id = $param['userInvestID'];
        $userID = $param['userID'];
        $money = $param['money'];
        $investID = $param['investID'];
        $productID = $param['productID'];
        $wallet_type = $param['wallet_type'];
        $wallet_road = $param['wallet_road'];
        $now = $param['createTime'];
        $accrual = DayAccrual::find()->where(array('userID'=>$userID))->andFilterWhere(['>', 'money', 0])->asArray()->orderBy("date $order")->all();
        $init_money = $money;
        //钱包明细
        $user_wallet = new UserWalletLog();
        $user_wallet->type = $wallet_type;
        $user_wallet->investID = $investID;
        $user_wallet->userInvestID = $user_invest_id;
        $user_wallet->money = $init_money;
        $user_wallet->createTime = $now;
        $user_wallet->userID = $userID;
        $user_wallet->road = $wallet_road;
        $user_wallet_result  = $user_wallet->save();
        if(!$user_wallet_result)
            return false;
        foreach($accrual as $v){
            $money = intval($v['money']);
            $id = $v['id'];
            if($money <= 0)
                continue;
            if($money < $init_money){
                $accrual_one = DayAccrual::findOne($id);
                $accrual_one->money = 0;
                $accrual_one->updateTime = $now;
                $one_result = $accrual_one->save();
                if(!$one_result)
                    return false;
                $investList = new UserInvestList();
                $investList->userID = $userID;
                $investList->investID = $investID;
                $investList->userInvestID = $user_invest_id;
                $investList->productID = $productID;
                $investList->money = $money;
                $investList->createTime = $now;
                $investList->accrualID = $id;
                $list_result = $investList->save();
                if(!$list_result)
                    return false;
                $init_money = $init_money - $money;
            }else{
                $accrual_one = DayAccrual::findOne($id);
                $accrual_one->money = $money - $init_money;
                $accrual_one->updateTime = $now;
                $one_result = $accrual_one->save();
                if(!$one_result)
                    return false;
                $investList = new UserInvestList();
                $investList->userID = $userID;
                $investList->investID = $investID;
                $investList->userInvestID = $user_invest_id;
                $investList->productID = $productID;
                $investList->money = $init_money;
                $investList->createTime = $now;
                $investList->accrualID = $id;
                $list_result = $investList->save();
                if(!$list_result)
                    return false;
                break;
            }
        }
        return true;
    }


    /*
     * 钱包扣钱
     */
    public static function transfer_deduct($param, $order = 'asc'){
        //更新用户余额 - 扣除账户余额
        $transfer_id = $param['id'];
        $userID = $param['userID'];
        $money = $param['money'];
        $desc = $param['desc'];
        $wallet_type = $param['wallet_type'];
        $wallet_road = $param['wallet_road'];
        $now = $param['createTime'];
        $transferUserID = $param['transferUserID'];
        $accrual = DayAccrual::find()->where(array('userID'=>$userID))->andFilterWhere(['>', 'money', 0])->asArray()->orderBy("date $order")->all();
        $init_money = $money;
        //钱包明细
        $user_wallet = new UserWalletLog();
        $user_wallet->type = $wallet_type;
        $user_wallet->gmID = $transfer_id;
        $user_wallet->money = $init_money;
        $user_wallet->createTime = $now;
        $user_wallet->userID = $userID;
        $user_wallet->road = $wallet_road;
        $user_wallet->desc = $desc;
        $user_wallet->gmID = $transfer_id;
        $user_wallet_result  = $user_wallet->save();
        if(!$user_wallet_result)
            return false;
        foreach($accrual as $v){
            $money = intval($v['money']);
            $id = $v['id'];
            if($money <= 0)
                continue;
            if($money < $init_money){
                $accrual_one = DayAccrual::findOne($id);
                $accrual_one->money = 0;
                $accrual_one->updateTime = $now;
                $one_result = $accrual_one->save();
                if(!$one_result)
                    return false;
                $investList = new UserTransferList();
                $investList->userID = $userID;
                $investList->transferID = $transfer_id;
                $investList->transferUserID = $transferUserID;
                $investList->money = $money;
                $investList->createTime = $now;
                $investList->accrualID = $id;
                $list_result = $investList->save();
                if(!$list_result)
                    return false;
                $init_money = $init_money - $money;
            }else{
                $accrual_one = DayAccrual::findOne($id);
                $accrual_one->money = $money - $init_money;
                $accrual_one->updateTime = $now;
                $one_result = $accrual_one->save();
                if(!$one_result)
                    return false;
                $investList = new UserTransferList();
                $investList->userID = $userID;
                $investList->transferID = $transfer_id;
                $investList->transferUserID = $transferUserID;
                $investList->money = $money;
                $investList->createTime = $now;
                $investList->accrualID = $id;
                $list_result = $investList->save();
                if(!$list_result)
                    return false;
                break;
            }
        }
        return true;
    }

    /*
    * 充值列表
    */
    public static function getList($userID, $page = 1, $limit = 10){
        if($page <= 0)
            $page = 1;
        if($limit <= 0)
            $limit = 10;
        $start = (intval($page) - 1) * $limit;
        $list = UserCharge::find()->where(['userID'=>$userID])->asArray()->limit($limit)
            ->offset($start)->orderBy('id desc')->all();
        $result = [];
        foreach($list as $k=>$v){
            $_list = [];
            $_list['createTime'] = date('Y-m-d H:i', $v['createTime']);
            $_list['money'] = CommonFunction::formatMoney($v['money']);
            $status = '处理中';
            $_list['status'] = $v['status'];
            $v['status'] == 0 && $status = '充值失败';
            $v['status'] == 1 && $status = '充值成功';
            $_list['info'] = $status;
            $result[] = $_list;
        }
        return $result;
    }

    /*
     * 充值状态
     */
    public static function chargeInfo($id, $userID){
        $info = UserCharge::findOne(['id'=>$id, 'userID'=>$userID]);
        if(!$info)
            return false;
        $endTime = $info['updateTime'];
        $createTime = $info['createTime'];

        $result['money'] = CommonFunction::formatMoney($info['money']);
        if($info['status'] != 0){
            $week = array("日","一","二","三","四","五","六");
            $tomorrow = strtotime("+1 day", $endTime);
            $result['tomorrow'] = date("m-d",$tomorrow) . ' 星期' . $week[date("w", $tomorrow)];

            $after = strtotime("+2 day", $endTime);
            $result['after'] = date("m-d",$after) . ' 星期' . $week[date("w", $after)];
            $week = array("日","一","二","三","四","五","六");
            $result['start'] = date("m-d",$createTime) . ' 星期' . $week[date("w", $createTime)];
        }
        $result['status'] = $info['status'];
        return $result;
    }

	//获取最新的充值记录
	public static function latestPay($userID,$id,$no)
	{
		$result=[];
		$data=UserCharge::find()->where("status = 1 and userID= $userID ");
		if($id)
		{
			$data=$data->andWhere(['id'=>$id]);
		}else
		{
			$data=$data->andWhere(['order'=>$no]);
		}
		
		if($data=$data->orderBy('updateTime desc')->limit(1)->asArray()->one())
		{
			$result['money']=sprintf("%.2f",$data['money']/100);
			$week = array("日","一","二","三","四","五","六");
			$result['today']=date("Y-m-d",$data['updateTime']) . ' 星期' . $week[date("w", $data['updateTime'] )];
			$result['tomorrow'] = date("Y-m-d",$data['updateTime']+86400) . ' 星期' . $week[date("w", $data['updateTime']+86400)];
			$result['after'] = date("Y-m-d",$data['updateTime']+86400*2) . ' 星期' . $week[date("w", $data['updateTime']+86400*2)];
		}
		return $result;
	}

    /*
     * 后台查询账户余额
     */
    public static function query_remainder($userID){
        $accrual = DayAccrual::find()->where(['userID'=>$userID])->andWhere('typeID!=15')->andFilterWhere(['>', 'money', 0])->groupBy('userID')
            ->select('SUM(money) as money')
            ->one();
        if($accrual){
            $accrual = $accrual->attributes;
            return intval($accrual['money']);
        }else
            return 0;
    }

    public static function test($userID){
        $is_staff = FinanceStaff::find()->where(['userID'=>$userID])->andWhere('companyID!=1')->count();
        if($is_staff > 0)
            $accrual = DayAccrual::find()->where(['userID'=>$userID])->andFilterWhere(['>', 'money', 0])->groupBy('userID')
                ->select('SUM(money) as money, userID')
                ->one();
        else
            $accrual = DayAccrual::find()->where(['userID'=>$userID])->andWhere('typeID!=15')->andFilterWhere(['>', 'money', 0])->groupBy('userID')
                ->select('SUM(money) as money, userID')
                ->one();
        if($accrual){
            $accrual = $accrual->attributes;
            return intval($accrual['money']);
        }else
            return 0;
    }
}